package cn.tyf.controller;

import cn.tyf.common.ConstAutoConfig;
import cn.tyf.dao.WeChatDao;
import cn.tyf.domain.User;
import cn.tyf.domain.WeChat;
import cn.tyf.service.UserService;
import cn.tyf.util.HttpClientUtil;
import cn.tyf.util.MD5Util;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/wx")
public class WeChatController {

    @Autowired
    private ConstAutoConfig constAutoConfig;
    @Autowired
    private WeChatDao weChatDao;
    @Autowired
    private HttpClientUtil httpClient;
    @Autowired
    private UserService userService;

    /**
     * 根据uid进行删除
     * @param uid
     */
    @RequestMapping("/delOpenId")
    @ResponseBody
    void delete(Integer uid,HttpServletRequest request){
        weChatDao.delete(uid);
    }

    /**
     * 根据uid查询
     * @param code
     * @return
     */
    @RequestMapping("/findOpenid")
    @ResponseBody
    User findByOpenid(HttpServletRequest request,String code){
        String url = constAutoConfig.getWxUrl();
        Map<String,String> parameter= new HashMap<>();
        parameter.put("appid",constAutoConfig.getWxAppid());
        parameter.put("secret",constAutoConfig.getWxSecret());
        parameter.put("js_code",code);
        parameter.put("grant_type",constAutoConfig.getWxGrantType());
        String openid = null;
        try {
            JSONObject wx = httpClient.doGet(url, null,parameter);
            openid = (String) wx.get("openid");
        } catch (URISyntaxException | IOException e) {
            e.printStackTrace();
        }
        WeChat weChat = weChatDao.findByOpenid(MD5Util.digest(openid));
        User user = null;
        if (weChat != null){
            user = userService.findById(weChat.getUid().toString());
        }
        HttpSession session = request.getSession();
        session.setAttribute("userLogin",user);
        session.setAttribute("type",false);
        return user;
    }
}
